<template>
  <div class="container" v-loading="loading">
    <div class="search-bar mb-16px">
      <el-input
          v-model="keyword"
          placeholder="请输入关键字"
          class="search-input"
      ></el-input>
      <el-button type="primary" @click="resetPage">查询</el-button>
      <el-button type="primary" @click="doEdit()">硬件发布</el-button>
    </div>
    <div class="card-wrapper">
      <Card
          v-for="item in list"
          :key="item.id"
          :data="item"
          @toggle="toggleStatus(item)"
          class="card-item"
      />

      <Empty v-if="!list.length" />
    </div>
    <el-pagination
        v-show="list.length"
        class="pagination"
        :total="total"
        layout="total, sizes, prev, pager, next"
        v-model:current-page="page.pageNum"
        v-model:page-size="page.pageSize"
        :page-sizes="[15, 30, 60, 120]"
    ></el-pagination>
    <el-dialog
        v-model="addVisible"
        width="60vw"
        :title="isAdd ? '新增' : '编辑'"
        :close-on-click-modal="false"
        @close="handleClose"
    >
      <el-form
          ref="formRef"
          :model="addData"
          :rules="rules"
          label-width="100"
          class="py-16px px-32px"
      >
        <el-form-item label="供应标题" prop="supplyTitle">
          <el-input v-model="addData.supplyTitle" placeholder="请输入供应标题"></el-input>
        </el-form-item>
        <el-form-item label="配置参数" prop="supplyDesc">
          <el-input
              type="textarea"
              v-model="addData.supplyDesc"
              placeholder="请输入配置参数"
              :rows="3"
          ></el-input>
        </el-form-item>

        <el-form-item label="品牌" prop="brandName">
          <el-input v-model="addData.brandName" placeholder="请输入品牌"></el-input>
        </el-form-item>
        <el-form-item label="型号" prop="modelName">
          <el-input v-model="addData.modelName" placeholder="请输入型号"></el-input>
        </el-form-item>
        <el-form-item label="货源性质" prop="goodsType">
          <el-radio-group v-model="addData.goodsType">
            <el-radio :label="1">现货</el-radio>
            <el-radio :label="2">期货</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="信息大图" prop="infoPicUrl">
          <ShardUpload
              v-model="addData.infoPicUrl"
              :limit="1"
              :fileSize="50"
              accept="image/*,video/*"
              :fileType="['png', 'jpg', 'jpeg', 'mp4', 'avi']"
              :extraTips="addData.infoType === 1 ? '轮播图尺寸： 1920 * 620' : ''"
              @change="handleFileChange"
              @uploadSuccess="uploadSuccess"
          />
        </el-form-item>
        <el-form-item label="销售数量" prop="goodsNumber">
          <el-input
              v-model="addData.goodsNumber"
              placeholder="请输入销售数量"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="单价" prop="goodsPrice">
          <el-input
              v-model="addData.goodsPrice"
              placeholder="请输入单价"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="单位" prop="priceUnit">
          <el-select v-model="addData.priceUnit" placeholder="请选择单位">
            <el-option
                v-for="option in goodsUnitOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item v-if="addData.goodsType === 2" label="到货时间" prop="arriveTime">
          <el-date-picker
              style="width: 60%"
              type="datetime"
              v-model="addData.arriveTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择到货时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item v-if="addData.goodsType === 2" label="批次量/次" prop="batchNum">
          <el-input
              v-model="addData.batchNum"
              placeholder="请输入每次交货的批次量"
              :maxlength="11"
              type="number"
          ></el-input>
        </el-form-item>
        <el-form-item v-if="addData.goodsType === 1" label="信息过期时间" prop="expireTime">
          <el-date-picker
              style="width: 60%"
              type="datetime"
              v-model="addData.expireTime"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="联系人" prop="contactUser">
          <el-input
              v-model="addData.contactUser"
              placeholder="请输入联系人"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="contactUserMobile">
          <el-input
              v-model="addData.contactUserMobile"
              placeholder="请输入联系电话"
              :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="交付地点" prop="goodsAddress">
          <el-input
              v-model="addData.goodsAddress"
              placeholder="请输入交付地点"
              :maxlength="11"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button
            type="primary"
            :loading="confirmLoading"
            @click="handleSubmit"
        >确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, inject } from 'vue';
import Card from "@/views/supply/components/supplyCard2.vue";
import {usePage, useLoading, useDict} from "@/hooks";
import ShardUpload from "@/components/FileUpload/shardUpload.vue";
import { ElMessage } from 'element-plus';

import {phoneValidator} from "@/utils/valid.js";
import {DICT_MAP} from "@/const/index.js";
const { list: goodsUnitOptions } = useDict(DICT_MAP.goods_price_unit);
const formRef = ref(null);
const { loading, setLoading } = useLoading();
const { loading: confirmLoading, setLoading: setConfirmLoading } = useLoading();
const $api = inject("$api");
const { page, total, resetPage } = usePage(15);
const isAdd = ref(false);
const addVisible = ref(false);
const keyword = ref("");
const list = ref([]);
const addData = ref({
  goodsName: "",
  contactUser: "",
  contactUserMobile: "",
  modelName: "",
  goodsPrice: "",
  priceUnit:"",
  arriveTime: "",
  expireTime: "",
  goodsAddress: "",
  goodsNumber: "",
  goodsType: "",
  paramDesc: "",
  infoPicUrl: "",
  status: 0,
});

// 表单验证规则
const rules = {
  supplyTitle: [{ required: true, message: '请输入供应标题', trigger: 'blur' }],
  supplyDesc: [{ required: true, message: '请输入配置参数', trigger: 'blur' }],
  brandName: [{ required: true, message: '请输入品牌', trigger: 'blur' }],
  modelName: [{ required: true, message: '请输入型号', trigger: 'blur' }],
  goodsType: [{ required: true, message: '请选择货源性质', trigger: 'change' }],
  infoPicUrl: [{ required: true, message: '请上传信息大图', trigger: 'blur' }],
  goodsNumber: [
    { required: true, message: '请输入销售数量', trigger: 'blur' },
    { pattern: /^[0-9]*$/, message: '销售数量只能输入数字', trigger: 'blur' }
  ],
  goodsPrice: [
    { required: true, message: '请输入单价', trigger: 'blur' },
    { pattern: /^[0-9]*\.?[0-9]*$/, message: '价格只能输入数字', trigger: 'blur' }
  ],
  priceUnit:[{ required: true, message: '请输入单位', trigger: 'blur' }],
  contactUser: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
  contactUserMobile: [{required: true, validator: phoneValidator}],
  batchNum: [{ required: false }, { pattern: /^[0-9]*$/, message: "批次量只能输入数字" }]
};

const getMySupply = async () => {
  setLoading(true);
  try {
    const { data: rows, total: resTotal } = await $api.supply.getSupplyNormalList({
      ...page.value,
      keyword: keyword.value,
    });
    list.value = rows;
    total.value = resTotal;
  } finally {
    setLoading(false);
  }
};

const doEdit = (row) => {
  isAdd.value = !row;
  if (row) {
    addData.value = { ...row };  // 复制传入的行数据
  } else {
    addData.value = {
      goodsName: "",
      contactUser: "",
      contactUserMobile: "",
      modelName: "",
      goodsPrice: "",  // 初始化单价
      priceUnit: "",
      arriveTime: "",
      expireTime: "",
      goodsAddress: "",
      goodsNumber: "",
      goodsType: "",
      paramDesc: "",
      infoPicUrl: "",
      status: 0,
    };
  }
  addVisible.value = true;
};


const toggleStatus = (item) => {
  item.status = Number(!item.status);
};

const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      setConfirmLoading(true);
      const submitData = {
        ...addData.value,
        provinceName: addData.value.provinceArr ? addData.value.provinceArr[0] : '',
        cityName: addData.value.provinceArr ? addData.value.provinceArr[1] : '',
        supplyType: 5,
        id: addData.value.id || undefined  // 仅在存在 ID 时传递
      };

      try {
        // 调用 addSupply API
        await $api.supply.addSupply(submitData);
        ElMessage.success('保存成功');
        addVisible.value = false;
        getMySupply();  // 刷新列表
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error("提交失败");
      } finally {
        setConfirmLoading(false);
      }
    }
  });
};

const handleFileChange = (file) => {
  // Handle file change if needed
};

const uploadSuccess = (file) => {
  if (file && file.url) {
    addData.value.infoPicUrl = file.url;
  } else {
    console.error('文件 URL 无效:', file);
  }
};

watch(
    () => page.value,
    () => {
      getMySupply();
    },
    {deep: true}
);

onMounted(() => {
  getMySupply();
});
</script>

<style scoped>
.container {
  padding: 20px;
}

.search-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
  margin: 18px;
  width: 500px;
}

.search-input {
  flex: 1;
  min-width: 200px;
}

.card-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  justify-content: center;
}

.card-item {
  flex: 1 1 calc(33.333% - 40px);
  max-width: calc(33.333% - 40px);
  box-sizing: border-box;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

@media (max-width: 768px) {
  .card-item {
    flex: 1 1 calc(50% - 40px);
    max-width: calc(50% - 40px);
  }
}

@media (max-width: 480px) {
  .card-item {
    flex: 1 1 100%;
    max-width: 100%;
  }
}
</style>